package com.luyuan.crm.task.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.faces.model.DataModel;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.CallBackRecord;
import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.service.CallBackRecordService;
import com.luyuan.crm.task.TaskDaily;
import com.luyuan.crm.task.TaskDailyService;
import com.luyuan.crm.task.TaskDailyStatus;
import com.luyuan.crm.user.Party;
import com.luyuan.crm.user.service.PartyService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.components.security.model.Role;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;
import com.ruijie.foundation.security.AppUserContext;
import com.ruijie.util.StringUtils;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;

@Scope("view")
@Component("taskDailyAction")
public class TaskDailyAction extends BaseAction implements InitializingBean {

    @Resource(name = "taskDailyService")
    private TaskDailyService taskDailyService;

    @Resource(name = "callBackRecordService")
    private CallBackRecordService callBackRecordService;

    @Resource(name = "partyService")
    private PartyService partyService;

    private TaskDaily criteria = new TaskDaily();

    private TaskDaily taskDaily;

    private CallBackRecord callBackRecord;

    // normal/delay
    private String excuteType = "normal";

    private Date startDate;

    private Date endDate;

    private Party party;

    public DataModel getTodayTask() {
        TablePage limit = TableContext.getTablePage();
        List<Order> orders = new ArrayList<Order>();

        CriteriaTemplate c = CriteriaTemplate.forClass(TaskDaily.class);
        RestrictionTemplate r = new RestrictionTemplate(true);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DATE, 1);
        c.add(r.le("expectedTime", calendar.getTime()));
        c.add(r.eq("taskStatus", TaskDailyStatus.CREATED));

        AppUser user = (AppUser) AppUserContext.getCurrentUser();
        Party party = partyService.getByAppUser(user);
        if (isClientManager()) {
            if (this.party == null) {
                c.add(r.isNull("party"));
            }
            else {
                c.add(r.eq("party", this.party));
            }
        }
        else {
            c.add(r.eq("party", party));
        }

        Page page = this.taskDailyService.pagedQuery(c, limit.getPage(), limit.getPageSize(), orders);
        return new PageDataModel(page);
    }

    private boolean isClientManager() {
        String scope = getRequestPath();
        if (!scope.endsWith("listTaskDailyForManager.jsf")) {
            return false;
        }

        AppUser appUser = (AppUser) AppUserContext.getCurrentUser();

        Set<Role> roles = appUser.getRoles();
        for (Role role : roles) {
            if ("售后经理".equals(role.getRoleName())) {
                return true;
            }
        }
        return false;
    }

    public DataModel getTableModel() {
        TablePage limit = TableContext.getTablePage();
        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<Order> orders = new ArrayList<Order>();
        for (TableOrder tableOrder : tableOrders) {
            Order order = tableOrder.toOrder();
            if (order != null) {
                orders.add(order);
            }
        }

        CriteriaTemplate c = CriteriaTemplate.forClass(TaskDaily.class);
        RestrictionTemplate r = new RestrictionTemplate(true);
        if (criteria.getTaskStatus() != null) {
            c.add(r.eq("taskStatus", criteria.getTaskStatus()));
        }
        if (startDate != null) {
            c.add(r.ge("expectedTime", startDate));
        }
        if (endDate != null) {
            c.add(r.le("expectedTime", endDate));
        }

        AppUser user = (AppUser) AppUserContext.getCurrentUser();
        Party party = partyService.getByAppUser(user);
        if (isClientManager()) {
            if (this.party == null) {
                c.add(r.isNull("party"));
                c.createCriteria("customer", "customer").add(
                        Restrictions.eq("customer.branchOffice", party.getBranchOffice()));
            }
            else {
                c.add(r.eq("party", this.party));
            }
        }
        else {
            c.add(r.eq("party", party));
        }
        Page page = this.taskDailyService.pagedQuery(c, limit.getPage(), limit.getPageSize(), orders);
        return new PageDataModel(page);
    }

    public TaskDaily getCriteria() {
        return criteria;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String id = getRequestParameter("id");
        if (StringUtils.isNotEmpty(id)) {
            taskDaily = taskDailyService.getTaskDailyById(id);
        }
        else {
            taskDaily = new TaskDaily();
            criteria.setTaskStatus(TaskDailyStatus.CREATED);
        }
    }

    public TaskDaily getTaskDaily() {
        return taskDaily;
    }

    public void createTaskDaily() {
        Party party = partyService.getByAppUser((AppUser) AppUserContext.getCurrentUser());
        taskDaily.setParty(party);
        taskDaily.setCreator(party.getUserName());

        taskDailyService.createTaskDaily(taskDaily);
    }

    public void updateTaskDaily() {
        taskDailyService.updateTaskDaily(taskDaily);
    }

    public void excuteTaskDaily() {
        callBackRecord = new CallBackRecord();
        callBackRecord.setMember((Member) taskDaily.getCustomer());
        callBackRecord.setParty(taskDaily.getParty());
        callBackRecord.setContent(taskDaily.getFeedback());
        if ("normal".equals(excuteType)) {
            callBackRecordService.addCallBackRecord(callBackRecord);
            taskDailyService.excuteTaskDaily(taskDaily);
        }
        else if ("delay".equals(excuteType)) {
            callBackRecordService.addCallBackRecord(callBackRecord);
            taskDailyService.updateTaskDaily(taskDaily);
        }
        else if ("cancel".equals(excuteType)) {
            callBackRecordService.addCallBackRecord(callBackRecord);
            taskDailyService.cancelTaskDaily(taskDaily);
        }
        addGlobalI18nMessage("操作成功！");
    }

    public String getExcuteType() {
        return excuteType;
    }

    public void setExcuteType(String excuteType) {
        this.excuteType = excuteType;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Party getParty() {
        return party;
    }

    public void setParty(Party party) {
        this.party = party;
    }
}
